<?php

namespace Portal\TutorBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Portal\TutorBundle\Entity\Tutor;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Portal\TutorBundle\Entity\TutorStep;
use Portal\MainBundle\Utils\customFunctions;
use Portal\TutorBundle\Entity\TutorSubject;
use Portal\TutorBundle\Entity\TutorConfirmHash;

class TutorStepController extends Controller {

    protected $step1 = 1;
    protected $step2 = 2;
    protected $step3 = 3;
    protected $step4 = 4;
    protected $step5 = 5;
    protected $step6 = 6;
    protected $notDone = 0;
    protected $done = 1;

    // $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
    public function becomeTutorAction() {
        /* $entity = new Tutor();
          $form = $this->createForm(new TutorType(), $entity);

          return $this->render('PortalTutorBundle:TutorStep:becomeTutor.html.twig', array(
          'entity' => $entity,
          'form' => $form->createView(),
          )); */
    }

    public function beginStepAction(Request $request) {
        $request = $request->request;
        $beginStepForm = $request->get('step');

        $tutor = new Tutor();

        $tutor->setUsername('');
    }

    public function step1Action() {
        $user = $this->container->get('security.context')->getToken()->getUser();

        $currenStep = $this->getStepById($user->getId());

        // Хичээлийн төрлийн лист
        $subjectCategoryList = $this->getSubjects();

        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step1);

        return $this->render('PortalTutorBundle:TutorStep:step1.html.twig', array(
                    'step' => $currenStep,
                    'subjectCategoryList' => $subjectCategoryList
        ));
    }

    public function step1submitAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();


        if (!isset($_POST['subjects'])) {
            // Хичээлийн төрлийн лист
            $subjectCategoryList = $this->getSubjects();
            return $this->render('PortalTutorBundle:TutorStep:step1.html.twig', array(
                        'step' => $this->step1,
                        'subjectCategoryList' => $subjectCategoryList
            ));
        }

        $subjects = $_POST['subjects'];


        $step2 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step1);
        if (!$step2) {
            // Хичээлийн төрлийн лист
            $subjectCategoryList = $this->getSubjects();
            return $this->render('PortalTutorBundle:TutorStep:step1.html.twig', array(
                        'step' => $this->step1,
                        'subjectCategoryList' => $subjectCategoryList
            ));
        }

        $this->saveTutorSubjects($user->getId(), $subjects);

        // Save step2 to step    
        $step2->setIsDone($this->done);
        $step2->setUpdatedAt(new \DateTime());

        $em = $this->getDoctrine()->getManager();
        $em->persist($step2);
        $em->flush();

        return $this->redirect(
                        $this->generateUrl("step2", array())
        );
    }

    public function step2Action() {
        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step2);
        $user = $this->container->get('security.context')->getToken()->getUser();
        $step2 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step2);
        if($step2->getIsDone() == 1){
            $isDone = 1;
        }else{
            $isDone = null;
        }
        return $this->render('PortalTutorBundle:TutorStep:step2.html.twig', array(
            'isDone' => $isDone
        ));
    }

    public function getQuestionAction() {

        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!$user) {
            return false;
        }

        $response = '';
        $questionArray = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->findQuestionId($this->container->getParameter('examQuestionCount'));

        $counter = 1;
        foreach ($questionArray AS $question) {


            $response .= '
            <ul style="list-style-type: none;"><b>Асуулт ' . $counter . ':</b> ' . $question['question'];
            $answers = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->findAnswerByQuesionId($question['id']);
            foreach ($answers AS $answer) {
                $response .='<li><input type="radio" name="' . $question['id'] . '" value="' . $answer['value'] . '" style="margin-top:0px;">&nbsp;' . $answer['text'] . '</li>';
            }

            $response .='</ul>';
            $counter++;
        }
        return new Response($response);
    }

    public function step2submitAction() {
        
        $user = $this->container->get('security.context')->getToken()->getUser();
        
        if (!$_POST) {
            $step2 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step2);            
            if($step2->getIsDone() == 0){
                $this->get('session')->setFlash('error', 'Уучлаарай та асуултанд хариулана уу.');
                return $this->redirect(
                                $this->generateUrl("step2", array())
                );
            }
            
        }
        
        foreach ($_POST AS $k => $v) {
            $k = (int) $k;
            $trueAnswer = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getTrueAnswer($k);
           
            if ($trueAnswer != $v) {
                $this->get('session')->setFlash('error', 'Уучлаарай асуултын хариулт таарахгүй байна.');
                return $this->redirect(
                                $this->generateUrl("step2", array())
                );
            }
        }
        
        
        $step2 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step2);
        if (!$step2) {
            return $this->render('PortalTutorBundle:TutorStep:step2.html.twig', array(
            ));
        }
        $step2->setIsDone($this->done);
        $step2->setUpdatedAt(new \DateTime());

        $em = $this->getDoctrine()->getManager();
        $em->persist($step2);
        $em->flush();

        return $this->redirect(
                        $this->generateUrl("step3", array())
        );
    }

    public function step3Action() {
        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step3);        
        return $this->render('PortalTutorBundle:TutorStep:step3.html.twig', array(
        ));
    }

    public function step3submitAction() {
        $user = $this->container->get('security.context')->getToken()->getUser();



        $step3 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step3);
        if (!$step3) {
            return $this->render('PortalTutorBundle:TutorStep:step3.html.twig', array(
            ));
        }

        $step3->setIsDone($this->done);
        $step3->setUpdatedAt(new \DateTime());

        $em = $this->getDoctrine()->getManager();
        $em->persist($step3);
        $em->flush();

        return $this->redirect(
                        $this->generateUrl("step4", array())
        );
    }

    public function step4Action() {
        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step4);

        return $this->render('PortalTutorBundle:TutorStep:step4.html.twig', array(
        ));
    }

    public function step4submitAction() {

        if (isset($_POST['resume']) && isset($_POST['title'])) {

            $user = $this->container->get('security.context')->getToken()->getUser();

            $step4 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step4);
            if (!$step4) {
                return $this->render('PortalTutorBundle:TutorStep:step4.html.twig', array(
                ));
            }

            $step4->setIsDone($this->done);
            $step4->setUpdatedAt(new \DateTime());

            $em = $this->getDoctrine()->getManager();
            $em->persist($step4);
            $em->flush();

            return $this->redirect(
                            $this->generateUrl("step5", array())
            );
        } else {

            $this->get('session')->setFlash('error', 'Уучлаарай энэ хичээл олдохгүй байна.');
            return $this->render('PortalTutorBundle:TutorStep:step4.html.twig', array(
            ));
        }
    }

    public function step5Action() {

        $user = $this->container->get('security.context')->getToken()->getUser();

        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step5);

        return $this->render('PortalTutorBundle:TutorStep:step5.html.twig', array(
                    'firstName' => $user->getFirstName(),
                    'lastName' => $user->getLastName(),
                    'url' => $this->container->getParameter('siteUrl')
        ));
    }

    public function step5submitAction() {
        if (isset($_POST['check1']) && isset($_POST['check2']) && isset($_POST['check3']) && isset($_POST['firstName']) && isset($_POST['lastName'])) {

            $user = $this->container->get('security.context')->getToken()->getUser();

            // check name
            if (customFunctions::clear($user->getFirstName()) != $_POST['firstName'] || customFunctions::clear($user->getLastName()) != $_POST['lastName']) {
                $this->get('session')->setFlash('error', 'Уучлаарай нэрээ зөв оруулана уу.');
                return $this->render('PortalTutorBundle:TutorStep:step5.html.twig', array(
                            'firstName' => $user->getFirstName(),
                            'lastName' => $user->getLastName(),
                            'url' => $this->container->getParameter('siteUrl')
                ));
            }


            // add step
            $step5 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step5);
            if (!$step5) {
                return $this->render('PortalTutorBundle:TutorStep:step5.html.twig', array(
                ));
            }

            $step5->setIsDone($this->done);
            $step5->setUpdatedAt(new \DateTime());

            $em = $this->getDoctrine()->getManager();
            $em->persist($step5);
            $em->flush();

            return $this->redirect(
                            $this->generateUrl("step6", array())
            );
        } else {
            $this->get('session')->setFlash('error', 'Уучлаарай та доорх нөхцөлүүдийг зөвшөөрч нэрээ зөв оруулана уу.');
            return $this->render('PortalTutorBundle:TutorStep:step5.html.twig', array(
                        'firstName' => $user->getFirstName(),
                        'lastName' => $user->getLastName(),
                        'url' => $this->container->getParameter('siteUrl')
            ));
        }
    }

    public function step6Action() {

        $user = $this->container->get('security.context')->getToken()->getUser();
        // add step
            $step6 = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getStepByTutorIdStep($user->getId(), $this->step6);
            if (!$step6) {
                return $this->render('PortalTutorBundle:TutorStep:step6.html.twig', array(
                ));
            }

            $step6->setIsDone($this->done);
            $step6->setUpdatedAt(new \DateTime());

            $em = $this->getDoctrine()->getManager();
            $em->persist($step6);
            $em->flush();
            
            
        $skiped = $this->findSkipedSteps();
        
        if ($skiped == null) {            

            $this->sendEmailToTutor($user);
        }

        // define step
        $this->container->get('security.context')->getToken()->getUser()->setStep($this->step6);

        return $this->render('PortalTutorBundle:TutorStep:step6.html.twig', array(
                    'skiped' => $skiped,
                    'email' => $user->getEmail()
        ));
    }

    private function findSkipedSteps() {
        //return null;
        $user = $this->container->get('security.context')->getToken()->getUser();
        $steps = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getSkipedStep($user->getId());
        return $steps;
    }

    private function sendEmailToTutor($user) {

        $hash = $this->generateHash();
        
        $confirm = new TutorConfirmHash();
        $confirm->setTutorId($user->getId());
        $confirm->setEmail($user->getEmail());
        $confirm->setHash($hash);
        $confirm->setIsActive(1);
        $confirm->setIsUsed(0);
        $confirm->setCreatedAt(new \DateTime());
        $confirm->setUpdatedAt(new \DateTime());
        $em = $this->getDoctrine()->getManager();
        $em->persist($confirm);
        $em->flush();
        
        $message = \Swift_Message::newInstance()
                ->setSubject('Sain baina uu')
                ->setFrom('odforme@gmail.com')
                ->setTo($user->getEmail())
                ->setContentType("text/html")
                ->setBody(
                'Сайн байна уу <b>' . $user->getFirstName() . '</b> та ' . $this->container->getParameter('siteUrl') . ' -д амжилттай бүртгэгдлээ та дараах линк дээр дарж бүртгэлээ баталгаажуулана уу.<br /><a href="' . $this->container->getParameter('siteUrl') . '/tutor/confirm/' . $hash . '">' . $this->container->getParameter('siteUrl') . '/tutor/confirm/' . $hash . '</a>'
        );
        $this->get('mailer')->send($message);

        return true;
    }

    private function getSubjects() {
        // Хичээлийн төрлийн лист
        $subjectCategoryList = $this->getDoctrine()->getEntityManager()->getRepository('PortalMainBundle:SubjectCategory')->getAll();
        if ($subjectCategoryList) {
            return $subjectCategoryList;
        } else {
            return null;
        }
    }

    private function getStepById($tutorId) {

        $tutor = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->checkIssetTutorId($tutorId);

        if (!$tutor) {
            for ($i = 1; $i <= $this->container->getParameter('stepCount'); $i++) {
                $tutorStep = new TutorStep();
                $tutorStep->setTutorId($tutorId);
                $tutorStep->setStep($i);
                $tutorStep->setIsDone($this->notDone);
                $tutorStep->setUpdatedAt(new \DateTime());
                $em = $this->getDoctrine()->getManager();
                $em->persist($tutorStep);
                $em->flush();
            }
            return $this->step1;
        } else {

            $tutorStep = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->getTutorNotDoneSteps($tutorId);
            return $tutorStep;
        }
    }

    private function saveTutorSubjects($tutorId, $subjects) {
        $tutorId = (int) $tutorId;
        foreach ($subjects AS $subjectId) {
            $subjectId = (int) $subjectId;
            $subjectCategoryId = $this->getDoctrine()->getEntityManager()->getRepository('PortalTutorBundle:TutorStep')->findSubjectCategoryId($subjectId);
            $tutorSubject = new TutorSubject();
            $tutorSubject->setTutorId($tutorId);
            $tutorSubject->setSubjectId($subjectId);
            $tutorSubject->setSubjectCategoryId($subjectCategoryId);
            $tutorSubject->setCreatedAt(new \DateTime());
            $em = $this->getDoctrine()->getManager();
            $em->persist($tutorSubject);
            $em->flush();
        }

        return true;
    }

    private function generateHash() {

        return 'aa';
    }
    
    

}
